package com.ruoyi.generator.util;




import com.itextpdf.text.Chunk;
import com.itextpdf.text.pdf.PdfWriter;
import com.lowagie.text.pdf.PdfEncodings;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ImageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.generator.domain.ReportSource;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.Units;
import org.apache.poi.wp.usermodel.Paragraph;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.List;

/**
 * @Author: WXM
 * @Description:
 * @Date: create in 2021/1/28 14:59
 */

public class WordUtils {


    static int pageW = 11907;//缇//A4宽度21cm,
    static int pageH = 16840;//缇//A4宽度29.7cm

    // word标准布局的页边距
    private static long LEFT_MARGIN = 1800L;
    private static long RIGHT_MARGIN = 1800L;
    private static long TOP_MARGIN = 1440L;
    private static long BOTTOM_MARGIN = 1440L;

    private static double maxWidthTwips = (pageW - LEFT_MARGIN - RIGHT_MARGIN);//8307
    private static double maxWidthCm = maxWidthTwips / 567.0;




    //全局字体
    private static String overallFontFamily = "楷体";
    private static Integer fontSizeTitle = 20;
    private static Integer fontSizeParagraph = 16;//三号
    private static Integer fontSizeContent = 14;//四号


    /**
     * poi转pdf
     * @param inputPath
     * @param outputPath
     * @return
     */
    public static String wordToPdfByReportId (String inputPath,String outputPath) {
        try {
            File inputFile = new File(inputPath);
            FileInputStream inputStream = new FileInputStream(inputFile);

            XWPFDocument document = new XWPFDocument(inputStream);

            PdfOptions options = PdfOptions.create();
            File outputFile = new File(outputPath);
            FileOutputStream outputStream = new FileOutputStream(outputFile);

            PdfConverter.getInstance().convert(document, outputStream, options);
            System.out.println("Word转PDF成功！");
            return outputPath;
        } catch (Exception ex) {
            System.err.print("转换失败："+ex.getMessage());
            return null;
        }


    }

    /**
     * itext转换
     * @param inputPath
     * @param outputPath
     * @return
     */

    public static String wordToPdfByReportIdByItext (String inputPath,String outputPath) {
        try {
            // 读取.docx文件
            FileInputStream inputStream = new FileInputStream(new File(inputPath));
            XWPFDocument document = new XWPFDocument(inputStream);

            // 创建.pdf文件
            com.itextpdf.text.Document pdfDocument = new com.itextpdf.text.Document();
            PdfWriter writer = PdfWriter.getInstance(pdfDocument, new FileOutputStream(outputPath));
            pdfDocument.open();

            // 将.docx文件的内容写入.pdf文件
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                Chunk chunk = new Chunk(paragraph.getText(), null);
                com.itextpdf.text.Paragraph pdfParagraph = new com.itextpdf.text.Paragraph(chunk);
                pdfDocument.add(pdfParagraph);
            }

            // 关闭.pdf文件
            pdfDocument.close();
            return outputPath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 报错，待完善
     * @param ruoyiProfile
     * @param inputPath
     * @param outputPath
     * @return
     */
    public static String wordToPdfByReportIdByXwpf(String ruoyiProfile, String inputPath, String outputPath) {
        try {
            // 读取docx文件
            XWPFDocument document = new XWPFDocument(new FileInputStream(inputPath));

            // 创建PDF文档
            PDDocument pdfDocument = new PDDocument();
            PDPage page = new PDPage();
            pdfDocument.addPage(page);

            // 创建PDF文件输出流
            FileOutputStream pdfFile = new FileOutputStream(outputPath);

            // 加载TrueType字体
            InputStream fontStream = new FileInputStream(ruoyiProfile+"/font/"+"Arial.ttf");
            PDType0Font font = PDType0Font.load(pdfDocument, fontStream,true);

            // 将docx内容写入PDF
            PDPageContentStream contentStream = new PDPageContentStream(pdfDocument, page);
            // 将docx内容写入PDF
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                // 处理段落内容
                String text = paragraph.getText();
                // 将段落内容写入PDF
                // TODO: 将文本写入PDF
                contentStream.beginText();
//                contentStream.setFont(PDType1Font.HELVETICA, 12);
                contentStream.setFont(font, 12);
                contentStream.newLineAtOffset(100, 700);
                contentStream.showText(text);
                contentStream.endText();
                contentStream.close();

            }

            for (XWPFTable table : document.getTables()) {
                // 处理表格内容
                // TODO: 将表格内容写入PDF
            }

            // 关闭docx文件
            document.close();

            // 保存PDF文件
            pdfDocument.save(pdfFile);
            pdfDocument.close();
            pdfFile.close();
            return outputPath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    //创建Word
    public static String getExcelWithTitle(String headImagePath, String ruoyiProfile, List<ReportSource> contents, String reportName, String getFontFamily, String fontFamilyTitle, String fontFamilyTitleSecond, String fontWeight, String fontWeightTitle, String fontWeightTitleSecond, String publishingDepartment, Integer fontSizeTitle, Integer getFontSizeParagraph, Integer getFontSizeContent, String eventTitle, String fontTitleColor, String style, Date startTime, Date endTime) throws IOException {

        XWPFDocument document = new XWPFDocument();
        //设置纸张大小及边距
        document = setPage(document);
        //文章字体及大小
        overallFontFamily=StringUtils.isNotEmpty(getFontFamily)?getFontFamily:overallFontFamily;
        fontSizeContent=getFontSizeContent!=0?getFontSizeContent:fontSizeContent;

        if(StringUtils.isNotEmpty(style)&&style.equals("2")){
            //设置报告主题
            document = setSubjectStyle2(document, reportName, fontTitleColor, fontSizeTitle, fontFamilyTitle, fontWeightTitle,getFontFamily,getFontSizeContent,headImagePath,publishingDepartment,eventTitle,startTime,endTime);
        }else{
            //设置报告主题
            document = setSubject(document, reportName, fontTitleColor, fontSizeTitle, fontFamilyTitle, fontWeightTitle);
            //设置发布部门
            document = setPublish(document, publishingDepartment, getFontFamily, fontWeight, getFontSizeContent);
            //创建报告标题下的横线
            document = setHeadline(document, headImagePath);
        }


        //段落
        for (int i = 0; i < contents.size(); i++) {
            ReportSource reportSource = contents.get(i);
            //一级标题
            String title = StringUtils.executeToChinese(i + 1) + "、" + reportSource.getTitle();
            document = setSecndTitle(document, title, fontFamilyTitleSecond, fontWeightTitleSecond, getFontSizeParagraph);

            //内容
            if (reportSource.getText() != null) {
                document=insertParagraph(document, reportSource.getText(), fontSizeContent, getFontFamily,fontWeight);
            } else if (reportSource.getImagePath() != null) {
                insertImageFromPath(document, reportSource.getImagePath(), "");
            }else if (reportSource.getTable() != null&&reportSource.getStyle()==4) {
                //创建表格（首发媒体溯源）
                createTable4(document, false, reportSource.getTable());
            } else if (reportSource.getTable() != null&&reportSource.getStyle()==3) {
                //创建表格（主要舆情）
                createTable3(document, false, reportSource.getTable());
            }else if (reportSource.getTable() != null&&reportSource.getStyle()==2) {
                //创建表格（事件脉络）
                createTable2(document, reportSource.getTable());
            } else if (reportSource.getTable() != null&&reportSource.getStyle()==1) {
                //创建表格（舆情导读）
                createTable1(document, reportSource.getTable());
            } else if (reportSource.getImageBase64() != null) {
                try {
                    insertImageFromBase64(document, reportSource.getImageBase64(), "");
                } catch (InvalidFormatException e) {
                    e.printStackTrace();
                }
            }


        }
        //增加页头，页脚
        String headerText = "舆情报告";
        String footerText = "本报告由系统智能生成";
        document = insertHeaderAndFooter(document, headerText, footerText);

        //保存word
        String docName;
        if (StringUtils.isNotEmpty(eventTitle)) {
            docName = DateUtils.dateTimeNow("yyyy-MM-dd") + eventTitle + "-" + Calendar.getInstance().getTimeInMillis() + ".docx";
        } else {
            docName = "report-" + UUID.randomUUID().toString().substring(0, 8) + ".docx";
        }
        FileOutputStream out = new FileOutputStream(new File(ruoyiProfile + "/" + docName));
        document.write(out);
        out.close();

        System.out.println("报告生成成功.");
        return docName;
    }

    private static XWPFDocument setSecndTitle(XWPFDocument document, String title, String fontFamilyTitleSecond, String fontWeightTitleSecond, Integer fontSizeParagraph) {
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.addCarriageReturn();

        XWPFRun runTitle = paragraph.createRun();
        runTitle.setText(title);
        runTitle.setFontSize(fontSizeParagraph);
        runTitle.setFontFamily(fontFamilyTitleSecond);
        if (StringUtils.isNotEmpty(fontWeightTitleSecond) && fontWeightTitleSecond.equals("bold")) {
            runTitle.setBold(true);
        }
        return document;
    }

    private static XWPFDocument setHeadline(XWPFDocument document, String headImagePath) {
            document = insertImageFromPath(document, headImagePath, "");

        return document;
    }

    private static XWPFDocument setPublish(XWPFDocument document, String publishingDepartment, String fontFamily, String fontWeight, Integer fontSize) {
        XWPFParagraph paragraph = document.createParagraph();
        paragraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun run = paragraph.createRun();
        run.setText(publishingDepartment + "   " + DateUtils.parseDateToStr("yyyy-MM-dd", new Date()));
//        run.setColor();
        run.setFontSize(fontSize);
        run.setFontFamily(StringUtils.isNotEmpty(fontFamily) ? fontFamily : overallFontFamily);
        if (StringUtils.isNotEmpty(fontWeight) && fontWeight.equals("bold")) {
            run.setBold(true);
        }
        return document;
    }

    private static XWPFDocument setSubject(XWPFDocument document, String reportName, String fontTitleColor, Integer fontSizeTitle, String fontFamilyTitle, String fontWeightTitle) {
//        添加标题
        XWPFParagraph titleParagraph = document.createParagraph();
//        设置段落居中
        titleParagraph.setAlignment(ParagraphAlignment.CENTER);
//        标题属性
        XWPFRun titleParagraphRun = titleParagraph.createRun();
        titleParagraphRun.setText(reportName);
        titleParagraphRun.setColor(fontTitleColor);
        titleParagraphRun.setFontSize(fontSizeTitle);
        titleParagraphRun.setFontFamily(StringUtils.isNotEmpty(fontFamilyTitle) ? fontFamilyTitle : overallFontFamily);
        if (StringUtils.isNotEmpty(fontWeightTitle) && fontWeightTitle.equals("bold")) {
            titleParagraphRun.setBold(true);
        }
        titleParagraphRun.addCarriageReturn();
        return document;
    }

    private static XWPFDocument setSubjectStyle2(XWPFDocument document, String reportName, String fontTitleColor, Integer fontSizeTitle, String fontFamilyTitle, String fontWeightTitle, String fontFamily, Integer getFontSizeContent, String headImagePath, String publishingDepartment, String eventTitle, Date startTime, Date endTime) {
        //提示
        XWPFParagraph tipParagraph = document.createParagraph();
        tipParagraph.setSpacingBetween(2);//行间距
        tipParagraph.setAlignment(ParagraphAlignment.RIGHT);
        XWPFRun tipRun = tipParagraph.createRun();
        tipRun.setText("内部报告，请勿外传");
        tipRun.setColor(fontTitleColor);
        tipRun.setFontSize(getFontSizeContent);
        tipRun.setFontFamily(StringUtils.isNotEmpty(fontFamilyTitle) ? fontFamilyTitle : overallFontFamily);
        tipRun.addCarriageReturn();
        tipRun.addCarriageReturn();
        tipRun.addCarriageReturn();
        tipRun.addCarriageReturn();

        //        添加标题
        XWPFParagraph titleParagraph = document.createParagraph();
        //        设置段落居中
        titleParagraph.setAlignment(ParagraphAlignment.CENTER);
        //        标题属性
        XWPFRun titleParagraphRun = titleParagraph.createRun();
        titleParagraphRun.setText("军情/舆情事件分析报告");
        titleParagraphRun.setColor(fontTitleColor);
        titleParagraphRun.setFontSize(fontSizeTitle);
        titleParagraphRun.setFontFamily(StringUtils.isNotEmpty(fontFamilyTitle) ? fontFamilyTitle : overallFontFamily);
        if (StringUtils.isNotEmpty(fontWeightTitle) && fontWeightTitle.equals("bold")) {
            titleParagraphRun.setBold(true);
        }
        //时间
        XWPFParagraph timeParagraph = document.createParagraph();
        //        设置段落居中
        timeParagraph.setAlignment(ParagraphAlignment.CENTER);
        //        标题属性
        XWPFRun timeRun = timeParagraph.createRun();
        timeRun.setText(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", new Date()));
        timeRun.setColor("000000");
        timeRun.setFontSize(14);
        timeRun.setFontFamily("楷体_GB2312");
        //横线
        setHeadline(document,headImagePath);
        //来源
        XWPFParagraph sourceParagraph = document.createParagraph();
        //        设置段落居中
        sourceParagraph.setAlignment(ParagraphAlignment.CENTER);
        //        标题属性
        XWPFRun sourceRun = sourceParagraph.createRun();
        sourceRun.setText(publishingDepartment);
        sourceRun.setColor(fontTitleColor);
        sourceRun.setFontSize(22);
        sourceRun.setFontFamily(fontFamilyTitle);
        sourceRun.addCarriageReturn();

        //空格
        XWPFParagraph emptyParagraph = document.createParagraph();
        emptyParagraph.setSpacingBetween(1.5);//行间距
        XWPFRun emptyRun = emptyParagraph.createRun();
        emptyRun.setText("");
        emptyRun.setFontSize(getFontSizeContent);
        emptyRun.setFontFamily(fontFamily);
        emptyRun.addCarriageReturn();
        emptyRun.addCarriageReturn();
        emptyRun.addCarriageReturn();
        emptyRun.addCarriageReturn();
        emptyRun.addCarriageReturn();

        //        监测事件
        XWPFParagraph eventParagraph = document.createParagraph();
        eventParagraph.setSpacingBetween(1.5);//行间距
        XWPFRun eventRun = eventParagraph.createRun();
        eventRun.setText("监测事件："+eventTitle);
        eventRun.setFontSize(getFontSizeContent);
        eventRun.setFontFamily(fontFamily);
        //检测时间

        XWPFParagraph startEndParagraph = document.createParagraph();
        startEndParagraph.setSpacingBetween(1.5);//行间距
        XWPFRun startEndRun = startEndParagraph.createRun();
        String time;
        if(startTime!=null&&endTime!=null){
            time="监测时间："+DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, startTime)+"-"+DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, endTime);
        }else{
            time="监测时间：";
        }
        startEndRun.setText(time);
        startEndRun.setFontSize(getFontSizeContent);
        startEndRun.setFontFamily(fontFamily);
        startEndRun.addCarriageReturn();
        startEndRun.addCarriageReturn();
        startEndRun.addCarriageReturn();
        //报送
        XWPFParagraph sendParagraph = document.createParagraph();
        XWPFRun sendRun = sendParagraph.createRun();
        sendRun.setText("报送：");
        sendRun.setFontSize(getFontSizeContent);
        sendRun.setFontFamily(fontFamily);
        sendParagraph.setBorderBottom(Borders.FANS);

        //抄送
        XWPFParagraph copyParagraph = document.createParagraph();
        XWPFRun copyRun = copyParagraph.createRun();
        copyRun.setText("抄送：");
        copyRun.setFontSize(getFontSizeContent);
        copyRun.setFontFamily(fontFamily);
        copyParagraph.setBorderBottom(Borders.SINGLE);

        //换一页
        XWPFParagraph paragraph = document.createParagraph();
        paragraph.setPageBreak(true);



        return document;
    }





    /**
     * 设置纸张大小及边距
     *
     * @param document
     * @return
     */
    private static XWPFDocument setPage(XWPFDocument document) {
        //         设置页面大小间距
        CTBody body = document.getDocument().getBody();
        if (!body.isSetSectPr()) {
            CTSectPr section = body.addNewSectPr();
            if (!section.isSetPgSz()) {
                CTPageSz size = section.addNewPgSz();
                size.setW(BigInteger.valueOf(pageW));
                size.setH(BigInteger.valueOf(pageH));
                //竖版
                size.setOrient(STPageOrientation.PORTRAIT);
            }

            if (!section.isSetPgMar()) {
                CTPageMar margin = section.addNewPgMar();
                margin.setBottom(BigInteger.valueOf(BOTTOM_MARGIN));
                margin.setTop(BigInteger.valueOf(TOP_MARGIN));
                margin.setLeft(BigInteger.valueOf(LEFT_MARGIN));
                margin.setRight(BigInteger.valueOf(RIGHT_MARGIN));
            }
        }
        return document;
    }
    public static void setSingleLineSpacing(XWPFParagraph para) {
        CTPPr ppr = para.getCTP().getPPr();
        if (ppr == null) ppr = para.getCTP().addNewPPr();
        CTSpacing spacing = ppr.isSetSpacing()? ppr.getSpacing() : ppr.addNewSpacing();
        spacing.setAfter(BigInteger.valueOf(0));
        spacing.setBefore(BigInteger.valueOf(50));
        spacing.setLineRule(STLineSpacingRule.AUTO);
        spacing.setLine(BigInteger.valueOf(240));
    }
    private static XWPFDocument insertParagraph(XWPFDocument document, String text, int fontSize, String fontFamily, String fontWeight) {


        XWPFParagraph paragraph = document.createParagraph();
        paragraph.setIndentationFirstLine(567);//缩进1cm
        paragraph.setSpacingBetween(1.5);//行间距
        XWPFRun run = paragraph.createRun();
        run.setText(text);
        run.setFontSize(fontSize);
        run.setFontFamily(fontFamily);
        if (StringUtils.isNotEmpty(fontWeight) && fontWeight.equals("bold")) {
            run.setBold(true);
        }
        run.addCarriageReturn();
        return document;
    }

    public static void insertImageFromUrl(XWPFDocument document, String inImageUrl, String imageName) throws IOException, InvalidFormatException {
        XWPFParagraph imageParagraph = document.createParagraph();
//        设置段落居中
        imageParagraph.setAlignment(ParagraphAlignment.CENTER);

        XWPFRun run = imageParagraph.createRun();
//        new一个URL对象
        URL url = new URL(inImageUrl);
//打开链接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置请求方式为"GET"
        conn.setRequestMethod("GET");
//超时响应时间为5秒
        conn.setConnectTimeout(5 * 1000);
//通过输入流获取图片数据
        InputStream is = conn.getInputStream();
//         因为FileInputStream没有重写reset() 所有将流转为了byte数组
        byte[] bs = IOUtils.toByteArray(is);
        BufferedImage image = ImageIO.read(new ByteArrayInputStream(bs));


        int width = MyUnits.pxToEMU(image.getWidth());
        int height = MyUnits.pxToEMU(image.getHeight());

//        EMU（英制公制单位）。1 EMU = 1/914400英寸= 1/36000 mm
        run.addPicture(new ByteArrayInputStream(bs), getPictureFormat(inImageUrl), imageName, width, height);
        is.close();
        //关闭连接
        conn.disconnect();
    }


    public static XWPFDocument insertImageFromPath(XWPFDocument document, String inImagePath, String imageName)  {
        InputStream is = null;
        try {
            is = new FileInputStream(inImagePath);
            XWPFParagraph imageParagraph = document.createParagraph();
//        设置段落居中
            imageParagraph.setAlignment(ParagraphAlignment.CENTER);
            XWPFRun run = imageParagraph.createRun();
            byte[] bs = IOUtils.toByteArray(is);
            BufferedImage image = ImageIO.read(new ByteArrayInputStream(bs));

            double width = (maxWidthCm * Units.EMU_PER_CENTIMETER);
            double height = (double)image.getHeight() / (double)image.getWidth()  * width ;

            run.addPicture(new ByteArrayInputStream(bs), getPictureFormat(inImagePath), imageName, (int)width, (int)height);
            run.addCarriageReturn();
            is.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        }
        return document;
    }





    public static void insertImageFromBase64(XWPFDocument document, String imageBase64, String imageName) throws IOException, InvalidFormatException {
        InputStream is = ImageUtils.BaseToInputStream(imageBase64.split(",")[1]);
        try {
            XWPFParagraph imageParagraph = document.createParagraph();
//        设置段落居中
            imageParagraph.setAlignment(ParagraphAlignment.CENTER);
            XWPFRun run = imageParagraph.createRun();
//         因为FileInputStream没有重写reset() 所有将流转为了byte数组
            byte[] bs = IOUtils.toByteArray(is);
            BufferedImage image = ImageIO.read(new ByteArrayInputStream(bs));
            int width = MyUnits.pxToEMU(image.getWidth()) / 2;
            int height = MyUnits.pxToEMU(image.getHeight()) / 2;
//        EMU（英制公制单位）。1 EMU = 1/914400英寸= 1/36000 mm
            run.addPicture(is, XWPFDocument.PICTURE_TYPE_PNG, imageName, width, height);
        } finally {
            is.close();
        }
    }

    public static void createTable4(XWPFDocument document, boolean unsetTblBorders, List<HashMap<String, String>> table) {

        //工作经历表格
        XWPFTable ComTable = document.createTable();

        //去表格边框
        if (unsetTblBorders) {
            ComTable.getCTTbl().getTblPr().unsetTblBorders();
        }

        //列宽自动分割
        CTTblWidth comTableWidth = ComTable.getCTTbl().addNewTblPr().addNewTblW();
        comTableWidth.setType(STTblWidth.DXA);
        comTableWidth.setW(BigInteger.valueOf(pageW - LEFT_MARGIN - RIGHT_MARGIN));

        for (int i = 0; i < table.size(); i++) {
            HashMap<String, String> data = table.get(i);
            if (i == 0) {
                //表头
                XWPFTableRow comTableRowOne = ComTable.getRow(0);
                comTableRowOne.setHeight(40);
                String[] title = data.keySet().toArray(new String[data.keySet().size()]);
                for (int j = 0; j < title.length; j++) {
                    if (j == 0) {
                        XWPFTableCell xwpfTableCell = comTableRowOne.getCell(0);
                        xwpfTableCell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
                        xwpfTableCell.setWidthType(TableWidthType.DXA);
                        xwpfTableCell.setText(title[j]);
                    } else {
                        XWPFTableCell xwpfTableCell = comTableRowOne.addNewTableCell();
                        xwpfTableCell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
                        xwpfTableCell.setWidthType(TableWidthType.DXA);
                        xwpfTableCell.setText(title[j]);
                    }

                }
            }
            //内容
            XWPFTableRow comTableRowTwo = ComTable.createRow();
            comTableRowTwo.setHeight(40);
            String[] v = data.values().toArray(new String[data.values().size()]);
            for (int j = 0; j < v.length; j++) {
                XWPFTableCell xwpfTableCell = comTableRowTwo.getCell(j);
                xwpfTableCell.setText(v[j]);
            }
        }

        //加个换行
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun paragraphRun = paragraph.createRun();
        paragraphRun.setText("\r");


    }

    public static void createTable3(XWPFDocument document, boolean unsetTblBorders, List<HashMap<String, String>> table) {

        //工作经历表格
        XWPFTable ComTable = document.createTable();

        //去表格边框
        if (unsetTblBorders) {
            ComTable.getCTTbl().getTblPr().unsetTblBorders();
        }

        //列宽自动分割
        CTTblWidth comTableWidth = ComTable.getCTTbl().addNewTblPr().addNewTblW();
        comTableWidth.setType(STTblWidth.DXA);
        comTableWidth.setW(BigInteger.valueOf(pageW - LEFT_MARGIN - RIGHT_MARGIN));

        for (int i = 0; i < table.size(); i++) {
            HashMap<String, String> data = table.get(i);
            if (i == 0) {
                //表头
                XWPFTableRow comTableRowOne = ComTable.getRow(0);
                comTableRowOne.setHeight(40);
                String[] title = data.keySet().toArray(new String[data.keySet().size()]);
                for (int j = 0; j < title.length; j++) {
                    if (j == 0) {
                        XWPFTableCell xwpfTableCell = comTableRowOne.getCell(0);
                        xwpfTableCell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
                        xwpfTableCell.setWidthType(TableWidthType.DXA);
                        xwpfTableCell.setText(title[j]);
                    } else {
                        XWPFTableCell xwpfTableCell = comTableRowOne.addNewTableCell();
                        xwpfTableCell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
                        xwpfTableCell.setWidthType(TableWidthType.DXA);
                        xwpfTableCell.setText(title[j]);
                    }

                }
            }
            //内容
            XWPFTableRow comTableRowTwo = ComTable.createRow();
            comTableRowTwo.setHeight(40);
            String[] v = data.values().toArray(new String[data.values().size()]);
            for (int j = 0; j < v.length; j++) {
                XWPFTableCell xwpfTableCell = comTableRowTwo.getCell(j);
                xwpfTableCell.setText(v[j]);
            }
        }

        //加个换行
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun paragraphRun = paragraph.createRun();
        paragraphRun.setText("\r");


    }


    public static void createTable2(XWPFDocument document, List<HashMap<String, String>> table) {

        for (int i = 0; i < table.size(); i++) {
            HashMap<String, String> map = new HashMap<>();
            map = table.get(i);

            XWPFParagraph paragraph1 = document.createParagraph();
            XWPFRun run = paragraph1.createRun();
            run.setText(map.get("序号") + "、"  + map.get("标题") + "[" + map.get("来源") + "]");
            run.setColor("000000");
            run.setFontSize(fontSizeContent);
            run.setBold(true);
            run.setFontFamily(overallFontFamily);

            XWPFParagraph paragraph2 = document.createParagraph();
            paragraph2.setIndentationFirstLine(567);
            run = paragraph2.createRun();
            run.setText(map.get("日期"));
            run.setColor("333333");
            run.setFontSize(fontSizeContent);
            run.setFontFamily(overallFontFamily);

            XWPFParagraph paragraph3 = document.createParagraph();
            paragraph3.setIndentationFirstLine(567);
            run = paragraph3.createRun();
            run.setText(map.get("内容"));
            run.setColor("000000");
            run.setFontSize(fontSizeContent);
            run.setFontFamily(overallFontFamily);


        }


    }


    public static void createTable1(XWPFDocument document, List<HashMap<String, String>> table) {

        for (int i = 0; i < table.size(); i++) {
            HashMap<String, String> map = new HashMap<>();
            map = table.get(i);

            XWPFParagraph paragraph1 = document.createParagraph();
            XWPFRun run = paragraph1.createRun();
            run.setText(map.get("序号") + "、" + "[" + map.get("属性") + "]" + map.get("标题") + "[" + map.get("来源") + "]");
            run.setColor("000000");
            run.setFontSize(fontSizeContent);
            run.setBold(true);
            run.setFontFamily(overallFontFamily);


            XWPFParagraph paragraph2 = document.createParagraph();
            run = paragraph2.createRun();
            run.setText(map.get("日期"));
            run.setColor("333333");
            run.setFontSize(fontSizeContent);
            run.setFontFamily(overallFontFamily);

            XWPFParagraph paragraph3 = document.createParagraph();
            paragraph3.setIndentationFirstLine(567);
            run = paragraph3.createRun();
            run.setText(map.get("内容"));
            run.setColor("000000");
            run.setFontSize(fontSizeContent);
            run.setFontFamily(overallFontFamily);

            if (map.get("链接") != null) {
                XWPFParagraph paragraph4 = document.createParagraph();
                run = paragraph4.createRun();
                run.setText("原文链接：" + map.get("链接"));
                run.setColor("333333");
                run.setFontSize(fontSizeContent);
                run.setFontFamily(overallFontFamily);
                run.addCarriageReturn();
            }
        }



    }


    public static XWPFDocument insertHeaderAndFooter(XWPFDocument document, String headerText, String footerText) {
        CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
        XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(document, sectPr);

        //添加页眉
        CTP ctpHeader = CTP.Factory.newInstance();
        CTR ctrHeader = ctpHeader.addNewR();
        CTText ctHeader = ctrHeader.addNewT();
        ctHeader.setStringValue(headerText);
        XWPFParagraph headerParagraph = new XWPFParagraph(ctpHeader, document);
        //设置为右对齐
        headerParagraph.setAlignment(ParagraphAlignment.RIGHT);
        XWPFParagraph[] parsHeader = new XWPFParagraph[1];
        parsHeader[0] = headerParagraph;
        policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT, parsHeader);

        //添加页脚
        CTP ctpFooter = CTP.Factory.newInstance();
        CTR ctrFooter = ctpFooter.addNewR();
        CTText ctFooter = ctrFooter.addNewT();
        ctFooter.setStringValue(footerText);
        XWPFParagraph footerParagraph = new XWPFParagraph(ctpFooter, document);

        headerParagraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFParagraph[] parsFooter = new XWPFParagraph[1];
        parsFooter[0] = footerParagraph;
        policy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, parsFooter);
        return document;
    }


    /**
     * 获取图片格式
     *
     * @param imgFile
     * @return
     */
    public static int getPictureFormat(String imgFile) {
        int format;
        if (imgFile.endsWith(".emf")) format = XWPFDocument.PICTURE_TYPE_EMF;
        else if (imgFile.endsWith(".wmf")) format = XWPFDocument.PICTURE_TYPE_WMF;
        else if (imgFile.endsWith(".pict")) format = XWPFDocument.PICTURE_TYPE_PICT;
        else if (imgFile.endsWith(".jpeg") || imgFile.endsWith(".jpg")) format = XWPFDocument.PICTURE_TYPE_JPEG;
        else if (imgFile.endsWith(".png")) format = XWPFDocument.PICTURE_TYPE_PNG;
        else if (imgFile.endsWith(".dib")) format = XWPFDocument.PICTURE_TYPE_DIB;
        else if (imgFile.endsWith(".gif")) format = XWPFDocument.PICTURE_TYPE_GIF;
        else if (imgFile.endsWith(".tiff")) format = XWPFDocument.PICTURE_TYPE_TIFF;
        else if (imgFile.endsWith(".eps")) format = XWPFDocument.PICTURE_TYPE_EPS;
        else if (imgFile.endsWith(".bmp")) format = XWPFDocument.PICTURE_TYPE_BMP;
        else if (imgFile.endsWith(".wpg")) format = XWPFDocument.PICTURE_TYPE_WPG;
        else {
            System.err.println("Unsupported picture: " + imgFile +
                    ". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg");
            System.err.println("不支持的图片格式: " + imgFile +
                    ". 仅支持 emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg 格式的图片");
            format = -1;
        }
        return format;
    }


}